<?php
namespace Admin\Model;

use Think\Model\RelationModel;

class EmployeeModel extends RelationModel
{
    protected $token = 'ofanap1448334221';

    protected $connection = array(
        'db_type'       =>  'mysql',
        'db_host'       =>  '114.55.30.131',
        'db_port'       =>  '3306',
        'db_name'       =>  'wxsmart',
        'db_user'       =>  'zhkj_crm',
        'db_pwd'        =>  'AdkdCGP7fHcjht5c',
        'db_charset'    =>  'utf8',
        'db_debug'      =>  true,
    );
    protected $tablePrefix = '';
    protected $tableName = 'tp_employee';

    protected $_auto = array(
    );

    public function chckEmployee($user){
        $userinfo = $this->where(array('userid' => $user['userid']))->find();
//                myDump($user);die;
        //数据库里没有，则入库
        $data = array(
            'userid'     => $user['userid'],
            'name'       => $user['name'],
            'department' => implode(",", $user['department']),
            'position'   => $user['position'],
            'mobile'     => $user['mobile'],
            'gender'     => $user['gender'],
            'weixinid'   => $user['weixinid'],
            'avatar'     => $user['avatar'],
            'status'     => $user['status'],
        );
        $remark = I('remark');
        if($remark)
            $data['remark'] = $remark;
//        dd($data);
        if(!$userinfo)
        {
//            echo '创建';
//            myDump($data);
            $id = $this->data($data)->add();
//            echo $id;
        }
        else
        {
//            echo '保存';
            $ok = $this->data($data)->where(array('userid' => $user['userid']))->save();
//            myDump($ok);
        }
    }


    public function getEmployee($userId){
        $ent = new \ZL\Wechat\EnterpriseHelper($this->token);
        $data = json_decode($ent->getUser($userId),true);
        if($data['errcode']==0)
            $this->chckEmployee($data);
        return $data;
    }

    public function chckHas($onLine){
        foreach ($onLine as $v){
            $data[$v['userid']] = $v;
        }
        $dbData = $this->select();
        foreach ($dbData as $v){
            if(!$data[$v['userid']]) {
                $this->delete($v['id']);
                echo '删除'.$v['name'].'<br/>';
            }else{
                $id = $this->data($data[$v['userid']])->where(array('id'=>$v['id']))->save();
                echo '保存'.$v['name'].'<br/>';
            }
        }
    }

    public function loading(){
        $excel = new \ZL\Excel();
        $path = I('path');
        $sheetNo = I('sheetNo',0);
        $startRow = I('startRow',1);
        $arr = $excel->getArr($path,$sheetNo,$startRow);
//        myDump($arr);die;
        $enter_helper = new \ZL\Wechat\EnterpriseHelper('ofanap1448334221');
        foreach ($arr as $k=>&$v) {
            if(!$v['weixinid'] || !$v['name'] || !$v['userid'])
                continue;
            if(!($v['gender'] == 1||$v['gender'] == 2))
                $v['gender'] = 1;
            $data = array();
            $data['name'] = $v['name'];
            $data['mobile'] = $v['mobile'];
            $data['userid'] = $v['userid'];
            $data['weixinid'] = $v['weixinid'];
            $data['gender'] = $v['gender'];
            $community = $v['community'];
            $data['department'] = $this->getDepID($community);
            if(!$data['department'])
                continue;
            $has = $this->where(array('name'=>$data['name']))->find();
            if($has){
                echo $data['name'];
                echo '--已经存在--';
                echo '<br/>';
                $this->updateOne($data);
                continue;
            }
//            myDump($data);die;
            $res = $enter_helper->createUser($data);
            $data = $this->getEmployee($data['userid']);
            $this->data(['remark'=>$v['remark']])->where(['userid'=>$v['userid']])->save();
            $res = json_decode($res,true);
            if($res['errcode']==0){
                myDump($v['name']);
                myDump($res);
            }else{
                myDump($v['name']);
                myDump($res['errmsg']);
            }
//            echo '<br/>';
        }
    }
    public function updateOne($data){
        $enter_helper = new \ZL\Wechat\EnterpriseHelper('ofanap1448334221');
        $enter_helper->updateUser($data);
        $this->getEmployee($data['userid']);
//        echo $data['name'];
//        echo '已更新'.$data['department'];
//        echo '<br/>';
    }

    public function getDepID($community){
//        $data = D('Depart')->select();
        $community = explode(',',$community);
        foreach ($community as $v) {
//            echo $v;
            $data[] = D('Depart')->where(array('name'=>array('like',"%$v%")))->find()['id'];
        }

        $data = array_unique($data);
        return $data;
    }


    public function getDeptList(){
        $ent = new \ZL\Wechat\EnterpriseHelper($this->token);
        $data = $ent->getDepartmentByID()['department'];
        $data = $this->_reSort($data);
    }

    public function _reSort($arr, $parentId=0, $level=1, $isClear=true){
        static $ret = array();
        if($isClear)
            $ret = array();
        foreach ($arr as $k => $v)
        {
            if($v['parentid'] == $parentId)
            {
                $v['level'] = $level;
                $ret[] = $v;
                $this->_reSort($arr, $v['id'], $level+1, FALSE);
            }
        }
        return $ret;
    }

    public function getLevel($id){
        $where['handler_man'] = $id;
        $where['step'] = 7;
//        $where['evaluate'] = array('NEQ',null);
        $sum = D('Service/WxOrder')->field('sum(evaluate) as sum')->where($where)->group('handler_man')->find()['sum'];
        $count = D('Service/WxOrder')->where($where)->count();
        return sprintf("%1\$.1f",$sum/$count);
    }

    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
    }
}
